/**
 * Created with JetBrains WebStorm.
 * User: Eric
 * Date: 02/02/13
 * Time: 17:17
 * To change this template use File | Settings | File Templates.
 */

/*
 * This file is a test of un Dao implementation
 * We need the mysql module
 */


// We create a connection
var connector = require('./connector');
var connection = connector.connection();
// We need our model
var Personage = require("./Personage");


var findPersonageByName = function (name, callback){ // we need a callback because the query is asynchronous

    var personage = new Personage(); // Our model that we can instanciate
    connection.query('SELECT * from personage where name = ?', [name], function(err, rows, fields) { // we do the query
        if (err) throw err; // if there is an error we throw it
        if (rows.length === 1){ // there is one result
            //process.stdout.write("personage found : " + email );
            personage.init(rows[0]); // we init the model with the row
        }else{
            process.stdout.write("personage not found : " + name );
            personage = null; // We didin't find the personage
        }
        callback(personage); // Callback basicaly it's the end of the controleur
    });

};


var savePersonage = function(personage, callback){

}



var persistPersonage = function(personage, callback){


    var post  = {name: personage.name, group: personage.group, coordinateX: personage.coordinateX, coordinateY: personage.coordinateY, coordinateZ: personage.coordinateZ,
        level:personage.level, money:personage.money, difficulty: personage.difficulty
    };

    if (personage.id == null){
        connection.query('INSERT INTO personage SET ?', post, function(err, rows, fields){

            if (err) throw err; // if there is an error we throw it

            personage.id = rows.insertId;
            callback(personage); // Callback basicaly it's the end of the controleur
        });
    }else{
        connection.query('update personage SET ? where id = ?',[post,personage.id], function(err, row, fields){


            if (err) throw err; // if there is an error we throw it

            var personage = new Personage();
            personage.init(row);

            callback(personage); // Callback basicaly it's the end of the controleur
        });
    }


};

exports.findPersonageByName = findPersonageByName;
exports.persistPersonage = persistPersonage;
exports.savePersonage = savePersonage;

/*
 SELECT t.coordinateX
 FROM   tile t
 WHERE  EXISTS (
 SELECT *
 FROM   tile tp
 WHERE  tp.personage is not null and
 t.coordinateX + 500 > tp.coordinateX and
 t.coordinateX - 500 < tp.coordinateX and
 t.coordinateY + 500 > tp.coordinateY and
 t.coordinateY - 500 < tp.coordinateY);
 */
